package com.jyxd.web.hiscz.service;

import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.error.JyxdException;
import com.jyxd.web.hiscz.dto.BodyDto;
import com.jyxd.web.hiscz.dto.HeaderDto;
import com.jyxd.web.hiscz.dto.RequestBodyDto;
import com.jyxd.web.hiscz.dto.ResponseHeadDto;
import com.jyxd.web.hiscz.dto.patient.demography.PatientIdentifierDto;
import com.jyxd.web.service.patient.PatientService;
import com.jyxd.web.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.jyxd.web.hiscz.Constant.HIS_ID_TYPE_PATIENT_ID;
import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;

@Service
public class HisUtilService {

    private static Logger logger = LoggerFactory.getLogger(HisUtilService.class);
    @Autowired
    private PatientService patientService;

    // 应传类型标识 int
    public static final String EXCEPTION_TYPE_INTEGER = "int";
    // 应传类型标识 string
    public static final String EXCEPTION_TYPE_STRING = "string";

    // 应传类型标识 date
    public static final String EXCEPTION_TYPE_DATE = "date";

    /**
     * 根据患者住院号唯一id查询患者信息
     *
     * @param body
     * @return
     */
    public Patient getPatient(BodyDto body) {
        errorIfEmpty(body.getPatientVisit(), "患者基本信息为空");
        errorIfEmpty(body.getPatientVisit().getVisitNumber(), "请求患者id不能为空");
       // List<PatientIdentifierDto> identifierList = body.getDemography().getPatientIdentifierList();
        logger.info("查询患者住院号为：" + body.getPatientVisit().getVisitNumber());
        Patient patient = patientService.getPatientByVisitId(body.getPatientVisit().getVisitNumber());
        return Objects.isNull(patient) ? null : patient;
    }

    /**
     * 获取患者院内标识
     *
     * @param identifierList
     * @return
     */
    public static String getVisitId(List<PatientIdentifierDto> identifierList) {
        if (CollectionUtils.isEmpty(identifierList)) {
            throw new JyxdException("患者id列表为空");
        }
        for (PatientIdentifierDto patientIdentifier : identifierList) {
            if (StringUtils.equals(patientIdentifier.getIdType(), HIS_ID_TYPE_PATIENT_ID)) {
                return patientIdentifier.getIdNumber();
            }
        }
        throw new JyxdException("患者院内id为空");
    }

    /**
     * 判断公共参数不能为空
     *
     * @param request
     */
    public static void isRequestEmpty(RequestBodyDto request) {
        errorIfEmpty(request, "请求参数不能为空");
        errorIfEmpty(request.getRequest(), "请求参数request不能为空");
        errorIfEmpty(request.getRequest().getBody(), "请求参数Body不能为空");
        errorIfEmpty(request.getRequest().getBody().getEvent(), "事件code不存在");
    }

    /**
     * 获取事件code
     *
     * @return
     */
    public static String getEventCode(BodyDto body) {
        errorIfEmpty(body, "参数不存在");
        errorIfEmpty(body.getEvent(), "事件信息不存在");
        errorIfEmpty(body.getEvent().getEventCode(), "事件id不存在");
        return body.getEvent().getEventCode().getIdentifier();
    }

    /**
     * 获取map中的值并判空
     *
     * @param objectMap
     * @param key
     * @return
     */
    public static <T> T getIsNullObject(Map<String, Object> objectMap, String key, Class<T> clazz, String type) {
        if (CollectionUtils.isEmpty(objectMap)) {
            return null;
        }
        if (Objects.isNull(objectMap.get(key))) {
            return null;
        }
        try {
            return clazz.cast(objectMap.get(key));
        } catch (Exception e) {
            logger.info(key + "类型转换错误，请使用正确类型：" + type);
            return null;
        }
    }

    /**
     * his对接返回值
     *
     * @param head
     * @param ackCode
     * @param message
     * @return
     */
    public static ResponseHeadDto hisResponse(HeaderDto head, String ackCode, String message) {
        head.setAckCode(ackCode);
        head.setAckMessage(message);
        return new ResponseHeadDto(head);
    }

    public static ResponseHeadDto hisResponse(String ackCode, String message) {
        return new ResponseHeadDto(new HeaderDto(ackCode, message));
    }

    /**
     * 获取时间格式
     *
     * @param object
     * @return
     * @throws ParseException
     */
    public static Date getTime(Object object) {
        if (Objects.isNull(object)) {
            return null;
        }
        if (object instanceof String) {
            String timeStr = (String) object;
            if (StringUtils.isBlank(timeStr)) {
                return null;
            }
            try {
                return DateUtil.yyyyMMddHHmmssSdfToDate(timeStr);
            } catch (ParseException e) {
                logger.info("时间格式转换错误：" + timeStr);
                return null;
            }
        }
        return null;
    }

}
